<template>
    <view class="main">
        <z-paging ref="paging" v-model="dataList" use-page-scroll @query="queryList">
            <template #refresher="{refresherStatus}">
                <custom-refresher :status="refresherStatus" />
            </template>
            <template #loadingMoreNoMore>
                <custom-nomore />
            </template>
            <view class="bg-white contain">
                <view class="p-20 flex row-between">
                    <u-tag text="添加记录" type="success" @click="handleaddList('add')"></u-tag>
                    <text @click="goAllList">全部记录</text>
                </view>
            </view>
            <view class="p-l-20 m-t-20 bold">今日记录</view>
            <view class="p-20">
                <view class="item bg-white" v-for="(item,index) in dataList" :key="index">
                    <view class=" p-30 m-b-20 box_shadow br12">
                        <view class="bold x">
                            借出编号：{{item.lendingNo}}
                        </view>
                        <view class="flex col-center row-between ">
                            <view class="">
                                <view class="m-t-10">
                                    <span>
                                        借出人员：{{ item.lendingName }}
                                    </span>
                                </view>
                                <view class="m-t-10">
                                    <span>
                                        日期：{{ today }}
                                    </span>
                                </view>
                            </view>
                            <view class="m-t-60">
                                <span class="m-r-10"><u-tag text="详情" type="warning"
                                        @click="handleDetail(item.id)"></u-tag></span>
                                <span class="m-r-10"><u-tag text="编辑" type="primary"
                                        @click="openPopup('edit',item)"></u-tag></span>
                                <u-tag text="归还" type="primary" @click="handleReturn(item.id,item.status)"></u-tag>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <u-popup v-model=" showPopup" mode="right" :mask-close-able="false" length="85%">
                <view class="p-20">
                    <uni-forms :model="goodsInfo">

                        <uni-forms-item label="借出人员">
                            <uni-easyinput v-model="goodsInfo.lendingName" type="text" border="none"
                                placeholder="请输入借出人员" />
                        </uni-forms-item>
                        <uni-forms-item label="借出状态">
                            <uni-data-select v-model="goodsInfo.status" :localdata="statusList"></uni-data-select>
                        </uni-forms-item>
                        <uni-forms-item label="借出地址">
                            <uni-easyinput v-model="goodsInfo.lendingAddress" type="text" border="none"
                                placeholder="请输入借出地址" />
                        </uni-forms-item>
                        <uni-forms-item label="添加商品" v-if="openType == 'add'">
                            <view class="m-t-10">
                                <u-tag text="扫码添加" type="primary" @click="scanAddData"></u-tag>
                            </view>
                        </uni-forms-item>
                    </uni-forms>
                    <view class="" v-if="openType == 'add'">
                        <u-table>
                            <u-tr>
                                <u-th>商品编号</u-th>
                                <u-th>操作</u-th>
                            </u-tr>
                            <u-tr v-for="item in goodsInfo.bodyList" :key="item.productNo">
                                <u-td>
                                    <view class="flex col-center row-center" style="height:50rpx;width: 100%;">
                                        {{item.productNo}}
                                    </view>
                                </u-td>
                                <u-td>
                                    <view class="flex col-center row-center" style="height:50rpx;width: 100%;">
                                        <u-tag text="删除" type="error" @click="handleDel(item.productNo)"></u-tag>
                                    </view>
                                </u-td>
                            </u-tr>
                        </u-table>
                    </view>
                    <u-alert-tips :show="showAlertTips" type="error" @close="showAlertTips = false" title="提示"
                        :description="description" :close-able="true"></u-alert-tips>
                    <view class="flex row-around m-t-40">
                        <u-button @click="showPopup = false">取消</u-button>
                        <u-button type="primary" @click="handleData">保存</u-button>
                    </view>
                </view>
            </u-popup>

        </z-paging>
    </view>
</template>

<script setup>
    import {
        apiGetLendingList,
        apiUpdateLendingInfo,
        apiAddLendingInfo,
        apiReturnAllLending,
        apiGetGoodsByCode
    } from '@/api/index.js'
    import {
        ref
    } from 'vue'
    import {
        onLoad
    } from '@dcloudio/uni-app'
    import {
        onPageScroll,
        onReachBottom
    } from '@dcloudio/uni-app';
    import useZPaging from "@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js";

    const dataList = ref([])
    const paging = ref(null)
    const showPopup = ref(false)
    const isDisabled = ref(false)
    const showAlertTips = ref(false)
    const openType = ref('')
    const today = ref('')
    const description = ref('')
    const goodsInfo = ref({
        lendingNo: '',
        lendingName: '',
        status: '',
        lendingAddress: '',
        bodyList: []
    })
    const statusList = [{
        text: '商品借出',
        value: '1'
    }, {
        text: '直播选品',
        value: '2'
    }, {
        text: '直播借出',
        value: '3'
    }, {
        text: '拍照借出',
        value: '4'
    }, {
        text: '养护借出',
        value: '5'
    }]

    const goAllList = () => {
        uni.navigateTo({
            url: '/pages/home/lend/all-list'
        });

    }

    const queryList = (pageNo, pageSize) => {
        const params = {
            current: pageNo,
            pageSize: pageSize,
            today: today.value
        }
        apiGetLendingList(params).then(res => {
            paging.value.complete(res.data.records);
        }).catch(res => {
            paging.value.complete(false);
        })
    }
    //编辑
    const openPopup = (type, item) => {
        openType.value = type
        showPopup.value = true
        goodsInfo.value = item
    }
    //添加
    const handleaddList = (type) => {
        openType.value = type
        showPopup.value = true
        goodsInfo.value = {
            lendingNo: '',
            lendingName: '',
            status: '',
            lendingAddress: '',
            bodyList: []
        }
    }

    //扫码
    const scanAddData = () => {
        uni.scanCode({
            success: function(res) {
                handelTableData(res.result)
            }
        });
    }

    //处理重复
    const handelTableData = async (no) => {

        if (goodsInfo.value.bodyList.find(item => item.productNo == no)) {
            uni.$u.toast('此商品已存在')
            return
        }
        let res = await apiGetGoodsByCode({
            productNo: no
        })
        if (res.code == 200) {
            if (res.data != null) {
                let obj = {
                    productNo: no,
                    photoAddress: res.data.photoAddress,
                    brand: res.data.brand,
                    colour: res.data.colour,
                    productModel: res.data.productModel,
                    dialSize: res.data.dialSize,
                    handCircumferenceSize: res.data.handCircumferenceSize
                }
                goodsInfo.value.bodyList.push(obj)
                // formData.value.bodyList.push(goodsObj)
                productNo.value = '' // 清空扫码输入框
                uni.$u.toast('添加成功')
            } else {
                uni.$u.toast('该商品不在仓库中')
            }
        }
    }

    const handleDetail = (id) => {
        uni.navigateTo({
            url: `/pages/home/lend/detail?headId=${id}`
        })
    }
    //归还
    const handleReturn = (id, status) => {
        if (status == 0) {
            uni.$u.toast('已全部归还')
            return
        }
        uni.showModal({
            title: '提示',
            content: '确认归还该商品吗？',
            success: (res) => {
                if (res.confirm) {
                    apiReturnAllLending({
                        id
                    }).then(res => {
                        uni.$u.toast('归还成功')
                        paging.value.refresh()
                    }).catch(err => {
                        uni.$u.toast('归还失败')
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        })
    }

    //删除
    const handleDel = (no) => {
        goodsInfo.value.bodyList = goodsInfo.value.bodyList.filter(item => item.productNo != no)
    }
    //保存
    const handleData = async () => {
        try {
            if (openType.value == 'edit') {
                let res = await apiUpdateLendingInfo({
                    ...goodsInfo.value
                })
                if (res.code == 200) {
                    uni.$u.toast('保存成功')
                    paging.value.refresh()
                    setTimeout(() => {
                        showPopup.value = false
                    }, 1000)
                } else {
                    uni.$u.toast('保存失败')
                }
            } else {
                let res = await apiAddLendingInfo({
                    ...goodsInfo.value
                })
                if (res.code == 200) {
                    uni.$u.toast('保存成功')
                    paging.value.refresh()
                    setTimeout(() => {
                        showPopup.value = false
                    }, 1000)
                } else {
                    description.value = res.msg
                    showAlertTips.value = true
                    // uni.$u.toast('保存失败')
                }
            }

        } catch (err) {

        }
    }
    useZPaging(paging)
    onLoad(() => {
        let date = new Date().getTime()
        today.value = uni.$u.timeFormat(date, 'yyyy-mm-dd');
    })
</script>

<style lang="scss">
    .main {
        position: relative;
        padding-top: 100rpx;
    }

    .contain {
        width: 100%;
        z-index: 9999;
        position: fixed;
        top: 0;
    }
</style>